﻿using FriendAD.Core;
using FriendAD.Core.General;
using FriendAD.Core.Types;
using FriendAD.web.Areas.Member.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace FriendAD.web.Areas.Member.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        #region 相关对象
        private UserManager userManager;
        private AdManager adManager;
        private User _user;
        private User user
        {
            get
            {
                if (_user != null)
                {
                    return _user;
                }
                else
                {
                    _user = userManager.Find(u => u.UserName == User.Identity.Name.Trim());
                    return _user;
                }
            }
        }
        public HomeController()
        {
            userManager = new UserManager();
            adManager = new AdManager();
        } 
        #endregion

        private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }
        /// <summary>
        /// 用户区域主页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.list = getAdList();
            return View();
        }
        /// <summary>
        /// 获取广告列表，下拉框
        /// </summary>
        /// <returns></returns>
        public List<SelectListItem> getAdList()
        {
            int userid = user.UserID;
            List<SelectListItem> list = new List<SelectListItem>();
            List<Ad> ad = adManager.FindList(m => m.UserId == userid).ToList();
            foreach (var item in ad)
            {
                list.Add(new SelectListItem()
                {
                    Text = item.Title,
                    Value = item.AdID.ToString()
                });
            }
            return list;
        }
        public PartialViewResult ArticleInfo(string id = "0")
        {
            string url = "http://weixin.sogou.com/pcindex/pc/pc_{0}/pc_{0}.html";
            return PartialView(Spider.getArticleList(String.Format(url, id)));
        }
        #region 文章生成

        /// <summary>
        /// 生成文章
        /// </summary>
        /// <returns></returns>
        public RedirectToRouteResult SaveArticle(string url, string adloca, string wechat,int adid)
        {
            //判断广告是否存在
            if (string.IsNullOrEmpty(url)|| string.IsNullOrEmpty(adloca) || string.IsNullOrEmpty(wechat))
            {
                return RedirectToAction("index");
            }
            if (!adManager.CheckAd(adid,User.Identity.Name.Trim()))
            {
                return RedirectToAction("index");
            }
            //获取文章信息
            Article article = Spider.getArticle(url);
            //获取广告信息
            Ad ad = adManager.Find(adid);
            Info info = new Info();
            try
            {

                //生成相关信息
                info.Ad = ad;
                info.location = Convert.ToInt32(adloca);
                info.wechatStatus = Convert.ToInt32(wechat);
                info.wechatID = article.wechat;
                info.Content = article.Context;
                info.Title = article.Title;
                info.UserID = user.UserID;
                
            }
            catch (Exception)
            {
                return RedirectToAction("index");
            }
            InfoManager infomanage = new InfoManager();
            Core.Types.Response _res = infomanage.Add(info);
            if (_res.Code == 1)
            {
                return RedirectToRoute("Default",new {Controller="home",Action="a",id=((Info)_res.Data).ID });
            }
            return RedirectToAction("index");
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public RedirectToRouteResult SaveArticle(CreateArticleModelView post)
        {
            if (!adManager.CheckAd(post.ad, User.Identity.Name.Trim()))
            {
                return RedirectToAction("index");
            }
            //获取文章信息
            Article article = Spider.getArticle(post.url);
            //获取广告信息
            Ad ad = adManager.Find(post.ad);
            //生成相关信息
            Info info = new Info()
            {
                Ad = ad,
                location = post.loca,
                wechatStatus = post.wechatStatus,
                wechatID = article.wechat,
                Content = article.Context,
                Title = article.Title,
                UserID = user.UserID
            };
            InfoManager infomanage = new InfoManager();
            Core.Types.Response _res = infomanage.Add(info);

            if (_res.Code == 1)
            {
                return RedirectToRoute("Default", new { Controller = "home", Action = "a", id = ((Info)_res.Data).ID });
            }
            return RedirectToAction("index");
        }
        #endregion
        
        public ActionResult Article(int page=1,int pagesize=10)
        {
            Paging<Info> pages = new Paging<Info>() {
                PageIndex=page,
                PageSize=pagesize
            };
            InfoManager infomangage = new InfoManager();
            pages = infomangage.FindPageList(pages,o=>o.ID);
            return View(pages);
        }


        #region 登陆登出
        public ActionResult Logout()
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return Redirect(Url.Content("~/"));
        }
        /// <summary>
        /// 登陆页面
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModelView login, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                Response _resp = userManager.Verify(login.Accounts.Trim(' '), Security.SHA256(login.Password));
                if (_resp.Code == 1)
                {
                    User _user = userManager.Find(user => user.UserName == login.Accounts);
                    userManager.UpadateLoginInfo(_user.UserID, Request.UserHostAddress, DateTime.Now);
                    var _identity = userManager.CreateIdentity(_user, DefaultAuthenticationTypes.ApplicationCookie);
                    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = login.RememberMe }, _identity);
                    //来路跳转
                    if (string.IsNullOrEmpty(returnUrl)) return RedirectToAction("Index", "Home");
                    else if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl);
                    else return RedirectToAction("Index", "Home");
                }
                else ModelState.AddModelError("Password", "密码错误");
            }
            return View();
        }
        #endregion

        #region 注册

        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Reg()
        {
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Reg(User user)
        {
            return View();
        }
        #endregion
    }
}